package com.text.mqtt_text.mqtt;


import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.eclipse.paho.client.mqttv3.*;

public class MqttClientSample {
    /**
     @Resource
     DeviceService deviceService1;
     @Resource
     SensorService sensorService1;

     private static DeviceService deviceService;
     private static SensorService;

     @PostConstruct
     public void init() {
     deviceService = deviceService1;
     sensorService = sensorService1;
     }
     */
    //静态方法中使用@Resource注解的方式

    public static void main(String[] args) throws Exception {
        String broker = "ssl://k1a8gKQzYMD.iot-as-mqtt.cn-shanghai.aliyuncs.com:443";
        // 替换为你的MQTT代理地址和端口
        String clientId = "k207mAsl3XZ.aq869PFDav0hLWewinxo|securemode=2,signmethod=hmacsha256,timestamp=1740834896109|";
        // 客户端ID
        String username = "aq869PFDav0hLWewinxo&k207mAsl3XZ";
        // 用户名
        String password = "048fc57c3a66ff314590a50b748617b766216547868f5720e497421ce102a2eb";
        // 密码
        MqttClient client = new MqttClient(broker, clientId);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);

        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("Connection lost: " + cause.getMessage());
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                String s = new String(message.getPayload());
                JsonElement element = JsonParser.parseString(s);
                JsonObject obj = element.getAsJsonObject();
                String deviceName = obj.getAsJsonPrimitive("deviceName").getAsString();
                JsonObject items = obj.getAsJsonObject("items");
                double currentHumidityValue = items.getAsJsonObject("CurrentHumidity").getAsJsonPrimitive("value").getAsFloat();
                double currentTemperatureValue = items.getAsJsonObject("CurrentTemperature").getAsJsonPrimitive("value").getAsFloat();
                System.out.println(deviceName + " " + currentHumidityValue + " " + currentTemperatureValue);

                //可以写一些数据库操作
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                System.out.println("Delivery complete");
            }
        });

        client.connect(options);
        // 替换为传感器设备上传数据的Topic
        client.subscribe("/k207mAsl3XZ/aq869PFDav0hLWewinxo/user/tento");
        System.out.println("Connected and subscribed");

    }
}


